package capstone.tagit;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;

import android.util.Log;

public class AppClient {

	
	InetAddress server;
	Socket socket;
	int port;
	
	public AppClient(String address, int port){
		try {
			server = InetAddress.getByName(address);
			this.port = port;			
		} catch (Exception e) {}
	}
	public String query(){
		socket = new Socket();
		Log.v("Client", "Just entered query");
		String tagsList = new String("");
		try {
			socket.connect(new InetSocketAddress(server, port), 50000);
			DataOutputStream os = new DataOutputStream(socket.getOutputStream());
			InputStream is = socket.getInputStream();
			BufferedReader fromServer = new BufferedReader(new InputStreamReader(is));
			
			os.writeBytes("query\n");
			String tagLine = null;
			Log.v("Client","About to enter the while loop");
			while ((tagLine = fromServer.readLine()) != null){
				Log.v("Client","In the while loop");
				tagsList = tagsList.concat(tagLine + "\n");
			}
			socket.close();
		}catch(Exception e){}
		
		Log.v("Client","About to exit query");
		return tagsList;
		
	}
	public void writeToServer(Tag tag) {
		socket = new Socket();
		try {
			socket.connect(new InetSocketAddress(server, port), 50000);
			DataOutputStream os = new DataOutputStream(socket.getOutputStream());
			os.writeBytes(tag.getInfoString(new SimpleDateFormat("yyyy.MM.dd \'at\' HH:mm:ss z")));
			socket.close();
		} catch (Exception e) {}
		
		
	}
	
	public void closeConnection(){
		try {
			socket.close();
		} catch (Exception e) {}
	}

}
